import { PureComponent } from "react";
import { isNull } from "../../utils/helper"
import MyDatetime from "./MyForm/MyDatetime"
interface Props {
	isReset: boolean,
	getFieldDecorator: Function,
	field: string[],
	defaultFormData: object,
	label?: string,
	required?: any,
}
interface State {
	hasError: boolean,
	errorMsg: string
}
export default class MiSelect extends PureComponent<Props, State> {
	public state: State = {
		hasError: false,
		errorMsg: ""
	}
	componentWillReceiveProps(next: Props) {
		let { isReset: oldReset } = this.props;
		let { isReset: newReset } = next;
		if (oldReset !== newReset && newReset) {
			this.setState({
				hasError: false
			})
		}
	}
	render() {
		let { getFieldDecorator, field, defaultFormData, label, required } = this.props;
		let { hasError, errorMsg } = this.state;
		let isRequired = required == 1;
		return (
			<div>
				{
					getFieldDecorator(field[0], {
						initialValue: defaultFormData[field[0]],
						rules: [
							{
								validator: (rule, value, callback) => {
									if (isRequired) {
										if (isNull(value)) {
											if (!hasError) {
												this.setState({
													hasError: true,
													errorMsg: "请选择：" + label
												})
												callback("请选择：" + label)
											}
										}
										else {
											this.setState({
												hasError: false,
												errorMsg: ""
											})
											callback()
										}
									}
									callback()
								}
							}
						]
					})(
						<MyDatetime {...this.props} hasError={hasError} errorMsg={errorMsg} />
					)
				}
			</div>
		)
	}
}
